<!--
 * @Author: 贺永胜
 * @Date: 2022-06-13 22:48:25
 * @公众号: 百里青山
 * @LastEditors: 贺永胜
 * @LastEditTime: 2022-06-23 17:44:37
 * @Descripttion:
-->
<template>
  <div class='desktop-wrap'>
    <div class="time-value" v-show="item">
    hello
      <div class="title">距离{{item.title}}还有</div>
      <div class="time">{{timeVal}}</div>
    </div>
  </div>
</template>

<script>
import * as api from '@/api/todoItem.js'
export default {
  name: 'DesktopView',
  data () {
    return {
      item: {},
      timeVal: '',
      interval: null,
      num: 0
    }
  },
  watch: {
    // item: {
    //   handler (val) {
    //     this.item = val
    //   },
    //   immediate: true,
    //   deep: true
    // }
  },
  mounted () {
    this.getNextTime()
    setInterval(() => {
      this.timeVal = this.getTimeDiff(this.item.date)
    }, 1000)
  },
  methods: {
    getNextTime () {
      api.getTodoItem({
        sort: { date: 1 }
      }).then(res => {
        console.log(res)
        res = res || []
        const item = res.find(item => {
          return item.date > new Date().getTime()
        })
        this.item = item || item
      })
    },
    getTimeDiff (inputTime) {
      // 获取从1970年1月1日到现在的时间的毫秒数
      const nowTime = +new Date()
      // 获取输入时间的毫秒数
      const putTime = +new Date(inputTime)
      // 剩余时间总的毫秒数 除以 1000 变为总秒数
      const dec = (putTime - nowTime) / 1000
      // 得到天 格式化成前缀加零的样式
      let d = parseInt(dec / 60 / 60 / 24)
      d = d < 10 ? '0' + d : d
      // 得到小时 格式化成前缀加零的样式
      let h = parseInt(dec / 60 / 60 % 24)
      h = h < 10 ? '0' + h : h
      // 得到分钟 格式化成前缀加零的样式
      let m = parseInt(dec / 60 % 60)
      m = m < 10 ? '0' + m : m

      let s = parseInt(dec % 60)
      s = s < 10 ? '0' + s : s

      return `${d}天${h}时${m}分${s}秒`
    }
    // 获取目标时间差并格式化成天时分秒
    // getTimeDiff (date) {
    //   const timeDiff = new Date(date).getTime() - new Date().getTime()
    //   const day = Math.floor(timeDiff / (1000 * 60 * 60 * 24))
    //   const hour = Math.floor(timeDiff / (1000 * 60 * 60))
    //   const minute = Math.floor(timeDiff / (1000 * 60))
    //   const second = Math.floor(timeDiff / 1000)
    //   return `${day}天${hour}时${minute}分${second}秒`
    // }
    // getTimeDiff (date) {
    //   const now = new Date()
    //   const target = new Date(date)
    //   const diff = target - now
    //   const day = Math.floor(diff / (1000 * 60 * 60 * 24))
    //   const hour = Math.floor(diff / (1000 * 60 * 60))
    //   const minute = Math.floor(diff / (1000 * 60))
    //   const second = Math.floor(diff / 1000)
    //   return day + '天' + hour + '小时' + minute + '分' + second + '秒'
    // }
  }
}
</script>
<style lang="scss" scoped>
.desktop-wrap {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgb(83, 188, 233);
}
.time-value {
  position: absolute;
  bottom: 100px;
  right: 100px;
  font-size: 32px;
}
</style>
